var baseApp = angular.module( "base");
//check-radio
baseApp.directive('checkRadio', function(checkService) {
	return {
		restrict : 'EA',
		replace : true,
		scope : {
			json:"=",
			read:"=",
			val:"="
		},
		template :  '<span>'+
						'<div bindonce ng-repeat="(k,v) in json" class="mt7 fn inline-block">'+
							'<input type="radio" id="{{(name+k)}}" ng-modal="val" name="{{name}}" value="{{k}}">'+
							'<span><label ng-bind="v" class="pointer" for="{{(name+k)}}" style="line-height: 20px;margin: 0 5px;"></label></span>'+
						'</div>'+
					 '</span>',
		link : function(scope, elm, attrs) {
			scope.name = "radioName_" + new Date().getTime() + GetRandomNum(1000,100000);
			var input = elm.find("input");
			// 如果是数据字典类型,则需要去查询对应的数据json
			if(attrs["cat"]){
				scope.json = {};
				checkService.getDicByCode(attrs["cat"],function(json){
					window.setTimeout(function(){
						scope.$apply(function(){
							scope.json = json;
						});
					},10);
				});
			}
			
			function initICheck(input){
				if(scope.hasInit){
					return;
				}
				scope.hasInit = true;
				var skin = "minimal";
				var color = "green";
				if(color != 'square'){
					skin = skin + "-" + color;
				}
				input.iCheck({
				    checkboxClass: 'icheckbox_'+skin,
				    radioClass: 'iradio_'+skin,
				    increaseArea: '20%' // optional
				});
				input.on('ifChecked', function(event,a,b){
					  var val =  $(this).val();
					  window.setTimeout(function(){
						  scope.$apply(function(){
							  scope.val = val;
						  });
					  },10);
				});
				scope.$watch("val",function(n,o){
					if(n!==o){
//						$("input",elm).iCheck('uncheck');
						if(!n){
							$("input",elm).iCheck('uncheck');
						}else{
							$("#"+scope.name + scope.val,elm).iCheck('check');
						}
					}
				});
				// 如果一开始就有值
				if(scope.val){
					$("#"+scope.name + scope.val,elm).iCheck('check');
				}
				scope.$watch("read",function(n,o){
					if(n){
						input.iCheck('disable');
					}else{
						input.iCheck('enable');
					}
				});
			}
			if(input[0]){
				initICheck(input);
			}else{
				window["timer_"+scope.name] = window.setInterval(function(){
					input = elm.find("input");
			    	if(input[0]){
						initICheck(input);
			    		window.clearInterval(window["timer_"+scope.name]);  
			    	}
			    },20);
			}
		}
	};
})
//check-box
.directive('checkBox', function(checkService) {
	return {
		restrict : 'EA',
		replace : true,
		scope : {
			json:"=",
			read:"=",
			val:"="
		},
		template :  '<span>'+
						'<div bindonce ng-repeat="(k,v) in json" class="mt7 fn inline-block">'+   /*ui-popover="{p:\'top\',content:k,noWatch:true}"*/
							'<input type="checkbox" id="{{(name+getKey(k))}}" ng-modal="val" name="{{name}}" value="{{k}}" >'+ /*ui-popover="{content:v,noWatch:true}"*/
							'<span><label ng-bind="v" class="pointer" for="{{(name+getKey(k))}}" style="line-height: 20px;margin: 0 5px;"></label></span>'+
						'</div>'+
					 '</span>',
		link : function(scope, elm, attrs) {
			scope.name = "checkboxName_" + new Date().getTime() + GetRandomNum(1000,100000);
			var input = elm.find("input");
			var base = checkService;
			elm.hide();
			// 如果是数据字典类型,则需要去查询对应的数据json
			if(attrs["cat"]){
				scope.json = {};
				checkService.getDicByCode(attrs["cat"],function(json){
					window.setTimeout(function(){
						scope.$apply(function(){
							scope.json = json;
						});
					},20);
				});
			}
			scope.getKey = function(key){
				key = key.replaceAll("\\.","__");
				return key;
			}
			function initICheck(input){
				if(scope.hasInit){
					return;
				}
				scope.hasInit = true;
				var skin = "minimal";
				var color = "green";
				if(color != 'square'){
					skin = skin + "-" + color;
				}
				input.iCheck({
				    checkboxClass: 'icheckbox_'+skin,
				    radioClass: 'iradio_'+skin,
				    increaseArea: '20%' // optional
				});
				input.on('ifChanged', function(event,a,b){
					if(scope.inChange) return;
					  var val =  new Array();
					  input.each(function(i,e){
						  var el = $(e);
						  if(el.is(":checked")){
							  var tempVal = el.val();
//							  tempVal = tempVal.replaceAll("__","\.");
							  val.push(tempVal);
						  }
					  });
					  
					  scope.val = val.join(",");
//					  !scope.$$phase&&scope.$digest();
					  !scope.$root.$$phase&&scope.$root.$digest();
				});
				function setVal(n){
					if(n){
//						$("input",elm).iCheck('uncheck');
						n = n + "";
						var v = n.split(",");
						scope.inChange = true;
						input.each(function(i,e){
							  $(e).iCheck('uncheck');
						});
						for ( var i = 0 ; i < v.length ; i++ ) {
							$("#"+scope.name + scope.getKey(v[i]),elm).iCheck('check');
                        }
						scope.inChange = false;
					}else{
						input.each(function(i,e){
							  $(e).iCheck('uncheck');
						});
					}
				}
				scope.$watch("val",function(n,o){
					setVal(n);
				});
				scope.$watch("read",function(n,o){
					if(n){
						input.iCheck('disable');
					}else{
						input.iCheck('enable');
					}
				});
				scope.$watch("json",function(n,o){
					if(n){
						//debugger;
						//setVal(scope.val);
					}
				},true);
				elm.show();
			}
			if(input[0]){
				initICheck(input);
			}else{
				window["timer_"+scope.name] = window.setInterval(function(){
					input = elm.find("input");
			    	if(input[0]){
						initICheck(input);
			    		window.clearInterval(window["timer_"+scope.name]);  
			    	}
			    },10);
			}
		}
	};
})


//check-box-list
.directive('checkBoxList', function($compile,checkService) {
	return {
		restrict : 'EA',
		replace : true,
		scope : {
			list:"=",
			read:"=",
			key:"=",
			title:"=",
			val:"="
		},
		template :  '<span><check-box json="json" read="read" val="val"></check-box></span>',
		link : function(scope, elm, attrs) {
			if(scope.list){
				var json = {};
				for ( var i = 0 ; i < scope.list.length ; i++ ) {
	                json[scope.list[i][scope.key]] = scope.list[i][scope.title];
                }
				scope.json = json;
			}
		}
	};
})

//check-box-all
.directive('checkBoxAll', function(checkService) {
	return {
		restrict : 'EA',
		replace : true,
		scope : {
			list:"=",
			ngChange:"=",
			parent:"=",
			ngModel:"="
		},
		template :  '<span >'+
							'<input type="checkbox" ng-model="ngModel">'+
					 '</span>',
		link : function(scope, elm, attrs) {
			scope.name = "checkboxNameAll_" + new Date().getTime() + GetRandomNum(1000,100000);
			var input = elm.find("input");
			elm.hide();
			function initICheck(input){
				var skin = "minimal";
				var color = "green";
				if(color != 'square'){
					skin = skin + "-" + color;
				}
				input.iCheck({
				    checkboxClass: 'icheckbox_'+skin,
				    radioClass: 'iradio_'+skin,
				    increaseArea: '20%' // optional
				});
				input.on('ifChanged', function(event,a,b){
					if(scope.inChange) return;
					  scope.$apply(function(){
						  scope.ngModel = input.is(":checked");
						  scope.ngChange&&scope.ngChange.call(this,scope.ngModel,scope.list,scope.parent);
					  });
				});
				elm.show();
			}
			if(input[0]){
				initICheck(input);
			}else{
				window["timer_"+scope.name] = window.setInterval(function(){
					input = elm.find("input");
			    	if(input[0]){
						initICheck(input);
			    		window.clearInterval(window["timer_"+scope.name]);  
			    	}
			    },10);
			}
		}
	};
})
//check-box-single
.directive('checkBoxSingle', function(checkService) {
	return {
		restrict : 'EA',
		replace : true,
		scope : {
			ngModel:"="
		},
		template :  '<span >'+
							'<input type="checkbox" ng-model="ngModel"  ng-if="(type==\'box\')">'+
							'<input type="radio" ng-model="ngModel" ng-if="(type==\'radio\')">'+
					 '</span>',
		link : function(scope, elm, attrs) {
			scope.name = "checkboxNameSingle_" + new Date().getTime() + GetRandomNum(1000,100000);
			scope.type = attrs["type"];
			var input = elm.find("input");
			elm.hide();
			function initICheck(input){
				if(scope.hasInit){
					return;
				}
				scope.hasInit = true;
				var skin = "minimal";
				var color = "green";
				if(color != 'square'){
					skin = skin + "-" + color;
				}
				input.iCheck({
				    checkboxClass: 'icheckbox_'+skin,
				    radioClass: 'iradio_'+skin,
				    increaseArea: '20%' // optional
				});
				input.on('ifChanged', function(event,a,b){
					if(scope.inChange) return;
					  scope.$apply(function(){
						  scope.ngModel = input.is(":checked");
					  });
				});
				$(input).iCheck('uncheck');
				scope.$watch("ngModel",function(n,o){
					scope.inChange = true;
					if(n){
						$(input).iCheck('uncheck');
						$(input).iCheck('check');
					}else{
						$(input).iCheck('check');
						$(input).iCheck('uncheck');
					}
					scope.inChange = false;
				});
				elm.show();
			}
			if(input[0]){
				initICheck(input);
			}else{
				window["timer_"+scope.name] = window.setInterval(function(){
					input = elm.find("input");
			    	if(input[0]){
						initICheck(input);
			    		window.clearInterval(window["timer_"+scope.name]);  
			    	}
			    },10);
			}
		}
	};
})

//check-dic
// <check-dic key="'SYS_SQL_TYPE'" val="tmSqlDef.catType"></check-dic>
// 这个是提供给快速开发用的 不用加read
.directive('checkDic', function(checkService) {
    return {
        restrict : 'EA',
        replace : true,
        scope : {
            key:"=",
            val:"="
        },
        template :  '<select class="form-control  mwd200" ng-model="val" ng-options="k as v for (k,v) in json">'+
						'<option value="">请选择</option>'+
					'</select>',
        link : function(scope, elm, attrs) {
        	checkService.getDicByCode(scope.key,function(json){
                window.setTimeout(function(){
                    scope.$apply(function(){
                        scope.json = json;
                    });
                },20);
            });
            scope.$watch("val",function(n,o){
				if(angular.isNumber(scope.val)){
					scope.val = scope.val + "";
				}
            	elm.trigger("blur");
            })
        }
    };
})
.service("checkService",function(baseService){
	var service = {
		// 根据字典编码获取字典列表
        getDicByCode : function(typeCode,callback){
        	var that = this;
        	if(that[typeCode] && that[typeCode].hasLoad){
        		that[typeCode].loadTime = that[typeCode].loadTime || 0;
        		if(that[typeCode].json){
        			callback&&callback.call(that,that[typeCode].json);
            		return that[typeCode].json;
        		}else{
        			// 如果10秒还没有返回
        			if(that[typeCode].loadTime<10000){
        				that[typeCode].loadTime += 200;
        				window.setTimeout(function(){
            				that.getDicByCode(typeCode,callback);
            			},200);
        			}
        			return that[typeCode].json;
        		}
        	}
        	
			that[typeCode] = {hasLoad:true};
			
			// 这里需要同步获取数据
			$.ajax ( {
		        url : __ctx + "/sys/dataDict/getDictData?dictKey="+typeCode ,
		        // data : JSON.stringify(res),
		        type : 'POST' ,
		        contentType : 'application/json' ,
		        dataType : 'json' ,
		        async : false ,
		        success : function ( rsp ) {
		        	if(rsp.data && rsp.data.length>0){
	        			var json = {};
	        			for(var i = 0 ; i < rsp.data.length ; i++ ){
	        				json[rsp.data[i].key] = rsp.data[i].name;
	        			}
	        			that[typeCode].json = json;
	        			callback&&callback.call(that,json);
	        		}else{
						that[typeCode].json = {};
	        			callback&&callback.call(that,json);
	        		}
		        }
			 } );
        },
	}
	return service;
})